package com.atguigu.search.service.impl;


import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.search.config.GulimallElasticSearchConfig;
import com.atguigu.search.constants.EsConstant;
import com.atguigu.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModel) throws IOException {

        //1. 给ES创建一个索引 product
        BulkRequest bulkRequest = new BulkRequest();
        //2. 构造请求
        for (SkuEsModel esModel : skuEsModel) {
            //设置索引
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            //设置索引id
            indexRequest.id(esModel.getSkuId().toString());
            //3. 编写dsl语句
            indexRequest.source(JSON.toJSONString(esModel), XContentType.JSON);

            bulkRequest.add(indexRequest);

        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
        //TODO 是否出现错误
        boolean hasFailures = bulk.hasFailures();
        if (hasFailures) {

            List<String> collect = Arrays.stream(bulk.getItems()).map(item -> item.getId()).collect(Collectors.toList());
            log.error("商品上架错误, {}", collect);
        }
        return hasFailures;
    }
}
